<?php

$host = '127.0.0.1';
$port = 7911;

define('ROOT_DIR', dirname(__FILE__));

require_once(ROOT_DIR.'/vendor/autoload.php');
require_once(ROOT_DIR.'/thrift/service/API.php');
require_once(ROOT_DIR.'/thrift/service/Utility.php');
require_once(ROOT_DIR.'/thrift/service/Types.php');

define('PLATFORM_WEB', 1);
define('PLATFORM_IOS', 2);
define('PLATFORM_ANDROID', 3);

define('STRUCT_USER', 1);
define('STRUCT_TARGET', 2);
define('STRUCT_DEVICE', 3);

header("Expires: Mon, 31 Jul 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

$services = array
(
    'login' => array('method' => 'get', 'params' => array(STRUCT_DEVICE)),
    'addRoster' => array('method' => 'post', 'params' => array(STRUCT_TARGET)),
    'getChatList' => array('method' => 'get', 'params' => array()),
    'sendChatMessage' => array('method' => 'post', 'params' => array(STRUCT_TARGET, 'message')),
    'readChatMessage' => array('method' => 'post', 'params' => array(STRUCT_TARGET)),
    'getChatHistory' => array('method' => 'get', 'params' => array(STRUCT_TARGET)),
);

function getFbToken()
{
    $wsse = $_SERVER['HTTP_X_WSSE'];
    $pos1 = strpos($wsse, 'AccessToken="') + strlen('AccessToken="');
    $pos2 = strpos($wsse, '"', $pos1);
    return substr($wsse, $pos1, $pos2 - $pos1);
}

function getPlatformId()
{
    if(stripos($_SERVER['HTTP_USER_AGENT'],'Android') !== false)
    {
        return PLATFORM_ANDROID;
    }
    elseif(stripos($_SERVER['HTTP_USER_AGENT'],'iPhone') != false ||
        stripos($_SERVER['HTTP_USER_AGENT'],'iPad') != false ||
        stripos($_SERVER['HTTP_USER_AGENT'],'iPod') != false)
    {
        return PLATFORM_IOS;
    }

    return PLATFORM_WEB;
}

function getIpAddress()
{
    return getenv('HTTP_CLIENT_IP')?:
           getenv('HTTP_X_FORWARDED_FOR')?:
           getenv('HTTP_X_FORWARDED')?:
           getenv('HTTP_FORWARDED_FOR')?:
           getenv('HTTP_FORWARDED')?:
           getenv('REMOTE_ADDR');
}

function sendThriftRequest($service, $params = array())
{
    global $host, $port;

    try
    {
        $transport = new \Thrift\Transport\TSocket($host, $port);
        $transport->setRecvTimeout(30000);
        $transport->setSendTimeout(30000);
        $transport->open();
        $protocol = new \Thrift\Protocol\TBinaryProtocol($transport);
        $client = new \thrift\service\APIClient($protocol);
        $response = call_user_func_array(array($client, $service), $params);
    }
    catch(Exception $e)
    {
        $response = $e->getMessage()."\n".$e->getTraceAsString();
    }

    if(isset($transport) && $transport != null && $transport->isOpen())
    {
        $transport->close();
    }

    return $response;
}

function run($service, $fbToken, $request)
{
    global $services;
    $params = array();
    $params[] = new \thrift\service\User(array('platformId' => getPlatformId(), 'fbToken' => $fbToken, 'ipAddress' => getIpAddress()));
    foreach($services[$service]['params'] as $param)
    {
        if($param == STRUCT_TARGET)
        {
            $profileId = @$request['profile_id'];
            $params[] = new \thrift\service\Target(array('profileId' => $profileId));
        }
        elseif($param == STRUCT_DEVICE)
        {
            $deviceName = @$request['device_name'];
            $osVersion = @$request['os_version'];
            $deviceToken = @$request['device_token'];
            $params[] = new \thrift\service\Device(array('deviceName' => $deviceName, 'osVersion' => $osVersion, 'deviceToken' => $deviceToken));
        }
        else
        {
            $params[] = $request[$param];
        }
    }
    echo sendThriftRequest($service, $params);
}

function explore()
{
    global $app;
    $service = $app->request->post('service');
    $fbToken = $app->request->post('fbToken');
    $request = json_decode($app->request->post('params'), true);
    run($service, $fbToken, $request);
}

function service()
{
    global $app;
    $service = $app->router->getCurrentRoute()->getName();
    $fbToken = getFbToken();
    $request = $app->request->params();
    run($service, $fbToken, $request);
}

$app = new \Slim\Slim();
$app->get('/', function(){echo 'Home page !!!';});
$app->post('/explore', 'explore');
foreach($services as $service => $request)
{
    $app->map('/'.$service, 'service')
        ->via(strtoupper($request['method']))
        ->name($service);
}
$app->run();
